package com.wxn.learncompose.pagers

import AnimState
import android.util.Log
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.isImeVisible
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat
import com.wxn.learncompose.R

/****
 * 几个动画示例
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable fun AnimPager() {


    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .clickable {
                    Log.d("AnimPager", "outer area click:: hiden keyboard")
                },
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            animIconBtn()
            AnimTextField()
            AnimIconButton()
            AnimTextField2()
            AnimImagePanel()
        }
    }
}

@Composable
fun AnimImagePanel() {
    var selectedAnimState : AnimState by remember{ mutableStateOf(AnimState.END) }
    val updateTransition = updateTransition(targetState = selectedAnimState, label = "switch_anim")
    val animAlpha by updateTransition.animateFloat(label = "") {
        when(it) {
            AnimState.START -> 0.0f
            AnimState.END -> 1.0f
        }
    }
    val heightAlpha by updateTransition.animateDp(label = "") {
        when(it) {
            AnimState.START -> 32.dp
            AnimState.END -> 0.dp
        }
    }

    Box(
        modifier = Modifier.size(128.dp).clickable {
            selectedAnimState = if (selectedAnimState == AnimState.END) {
                AnimState.START
            } else {
                AnimState.END
            }
        }
    ) {
        Image(
            painterResource(id = R.drawable.wallpaper), null,
            modifier = Modifier
                .size(128.dp)
                .clip(RoundedCornerShape(8.dp)),
            contentScale = ContentScale.Crop
        )

        Text(
            text = "点我",

            fontSize = TextUnit(24f, TextUnitType.Sp),
            color = Color.White,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.align(Alignment.Center).graphicsLayer {
                alpha = animAlpha
            }
        )

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(heightAlpha)
                .background(Color(0xFF5FB878),
                    RoundedCornerShape(0.dp, 0.dp, 8.dp, 8.dp))
                .alpha(1 - animAlpha)
                .align(Alignment.BottomCenter),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Center
        ) {
            Icon(Icons.Filled.ThumbUp, null, modifier = Modifier.size(24.dp),
                tint = Color.White)
            Spacer(modifier = Modifier.width(3.dp))
            Text(text = "已选择",
                fontSize = TextUnit(16f, TextUnitType.Sp),
                color = Color.White,
                fontWeight = FontWeight.Bold)
        }
    }
}


/*****
 * 基于 Animatable 实现控制TextFiled的键盘监听动画
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun AnimTextField2() {
    val focusManager = LocalFocusManager.current
    var inputText by rememberSaveable{ mutableStateOf("") }
    val isImeVisible = WindowInsets.isImeVisible
    var focused by rememberSaveable{ mutableStateOf(false) }
    LaunchedEffect(WindowInsets.isImeVisible) {
        focused = if (isImeVisible) { true
            } else { false }
    }
    var sizeVariable = remember { Animatable(0.0f) }
    LaunchedEffect(focused) {
        if (focused) { sizeVariable.animateTo(1.0f)
        } else { sizeVariable.animateTo(0.5f)
        }
    }
    TextField(value = inputText,
            onValueChange = {
                inputText = it
            },
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
        keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }), //关闭键盘并从 TextField 中清除焦点
        modifier = Modifier.fillMaxWidth(sizeVariable.value)
    )
}


/****
 * 使用Animatable实现的 红心Icon 动画
 */
@Composable
fun AnimIconButton() {
    var sizeVariable = remember{ Animatable(24.dp, Dp.Companion.VectorConverter) }
    var change by remember { mutableStateOf(false) }
    var flag by remember { mutableStateOf(false) }
    LaunchedEffect(change) { sizeVariable.animateTo( if (change) 32.dp else 24.dp) }
    if (sizeVariable.value == 32.dp) {
        change = false
    }

    IconButton(onClick = {
        change = true
        flag = !flag }) {
        Icon(Icons.Filled.Favorite,
            tint = if (flag) Color.Red else Color.Gray,
            contentDescription = "",
            modifier = Modifier.size(sizeVariable.value))
    }
}

/***
 * 获取焦点时，键盘谈起，显示长条的输入框
 * 失去焦点，键盘收起， 显示短条的输入框
 */
@Composable
@OptIn(ExperimentalLayoutApi::class)
private fun AnimTextField() {
    val focusManager = LocalFocusManager.current
    var keyboardState by rememberSaveable { mutableStateOf(false) }
    val imeVisible =
        WindowInsets.isImeVisible //Activity中要设置： //    WindowCompat.setDecorFitsSystemWindows(window, false)

    var inputText by rememberSaveable { mutableStateOf("") }
    var focusd by rememberSaveable { mutableStateOf(false) }
    val textSize by animateFloatAsState(targetValue = if (focusd) 1.0f else 0.5f)

    LaunchedEffect(WindowInsets.isImeVisible) {
        if (!imeVisible) {
            //软键盘收起
            Log.d("AnimPager", "imeVisible : false")
            keyboardState = false
            focusd = false
        } else {
            Log.d("AnimPager", "imeVisible : true")
            keyboardState = true
            focusd = true
        }
    }
    TextField(value = inputText,
        onValueChange = {
            inputText = it
        },
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
        keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }), //关闭键盘并从 TextField 中清除焦点
        modifier = Modifier
            .onFocusChanged { focusState ->
                focusd = focusState.hasFocus
                Log.d("AnimPager", "onFocusChanged : focusd = ${focusd}")
            }
            .fillMaxWidth(textSize)
    )
}

/***
 * 点击时有放大并且变成红色效果的心型icon
 */
@Composable
private fun animIconBtn() {
    var change by rememberSaveable { mutableStateOf(false) }
    var flag by rememberSaveable { mutableStateOf(false) }

    val iconSize by animateDpAsState(targetValue = if (change) 32.dp else 24.dp, label = "IconSize")
    if (iconSize == 32.dp) {
        change = false
    }

    IconButton(onClick = {
        flag = !flag
        change = true
    }) {
        Icon(
            Icons.Filled.Favorite, contentDescription = null,
            modifier = Modifier.size(iconSize),
            tint = if (flag) Color.Red else Color.Gray
        )
    }
}